package com.alianzamedica.controllers.prescription;

import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.objectsearch.sqlsearch.ObjectSearch;
import org.objectsearch.web.tools.Converter;
import org.w3c.dom.Document;

import com.alianzamedica.businessobject.Patient;
import com.alianzamedica.businessobject.Prescription;
import com.alianzamedica.tools.Enviroment;

/**
 * @author carlos
 * 
 */
public class SetPatientAction extends Action {

	@SuppressWarnings("unchecked")
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		HttpSession session = request.getSession();
		Prescription prescription = (Prescription) session
				.getAttribute("prescription");
		Enviroment env = Enviroment.getInstance();
		Document doc = env.getDocument();
		String val = request.getParameter("id");
		Integer id = Converter.string2Integer(val);
		Patient p = new Patient();
		p.setId(id);
		ObjectSearch search = new ObjectSearch(doc,
				"com.alianzamedica.connection.ConnectionImpl");
		Iterator<Patient> iterator = search.searchObjects(p).iterator();
		if (iterator.hasNext()) {
			@SuppressWarnings("unused")
			Patient patient = (Patient) iterator.next();
			if (prescription != null) {
				prescription.setPatientId(id);
			}

		}
		session.setAttribute("prescription", prescription);
		response
				.sendRedirect("/AlianzaMedica/admin/prescription/createPrescription.do");

		return null;
	}

}
